package com.zzwtel.autocode.template.model;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.zzwtel.autocode.util.PathUtil;

import us.codecraft.xsoup.Xsoup;

/**
 * 整个左菜单模型
 * @author yangtonggan
 * @date 2016-6-8
 */
public class LeftMenuModel {
	private List<FirstLevelMenuModel> childrenMenu = new ArrayList<FirstLevelMenuModel>();

	public List<FirstLevelMenuModel> getChildrenMenu() {
		return childrenMenu;
	}

	public void setChildrenMenu(List<FirstLevelMenuModel> childrenMenu) {
		this.childrenMenu = childrenMenu;
	}
	
	public LeftMenuModel parse(){		
		try{
			String root = PathUtil.getModelRoot();
			File file = new File(root+"menu/left-menu-model.xml");
			Document document = Jsoup.parse(file, "UTF-8");
			return fromDocument(document);		
		}catch(Exception e){
			throw new RuntimeException("菜单模型还没有生成，请先执行"+e);
		}
		
	}
	/**
	 * 从Document加载左菜单模型
	 * @return
	 */
	public LeftMenuModel fromDocument(Document document) throws RuntimeException{		
		Elements menus  = Xsoup.select(document, "//left-menu/first_level_menu").getElements();
		int size = menus.size();		
		for(int i = 0 ; i<size ; i++){
			Element child = menus.get(i);	
			FirstLevelMenuModel childMenu = new FirstLevelMenuModel();
			childMenu.fromElement(child, i);			
			childrenMenu.add(childMenu);	
		}		
		return this;
	}
	/**
	 * 把模型以xml字符串输出，便于检查模型加载是否正确
	 * @return
	 */
	public String toXml(){
		StringBuilder sb = new StringBuilder();
		sb.append("<?xml version='1.0' encoding='UTF-8'?>\n");
		sb.append("<left-menu>\n");  
		for(FirstLevelMenuModel menu : childrenMenu){			
			sb.append(menu.toXml());			
		}
		sb.append("</left-menu>\n");
		return sb.toString();
	}
	
	public static void main(String[] args){
		LeftMenuModel menu = new LeftMenuModel();
		menu = menu.parse();
		System.out.println(menu.toXml());
	}
}
